package com.j.lemon.learn.thread.collectionNotSafe;

import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author lijunjun
 * @Date 2019-04-17 17:06
 * @Description Set是非线程安全的例子，以及解决方法
 */
public class SetNotSafeDemo {
    public static void main(String[] args) {
//        Set<String> set = new HashSet<>();

//        使用CopyOnWriteArraySet
        Set<String> set = new CopyOnWriteArraySet<>();
        for (int i = 0; i < 30; i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,6));
                System.out.println(set);
            },String.valueOf(i)).start();
        }

        //hashset底层原理是hashMap，只不过只关心key
        new HashSet<>();
    }
}
